﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Net;
using System.Globalization;
using System.ComponentModel.Design.Serialization;
using System.Reflection;

namespace Argos.Design
{
	public class IPAddressConverter : TypeConverter
	{

		public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
		{
			return sourceType == typeof(string) || sourceType == typeof(byte[]);
		}

		public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
		{
			return destinationType == typeof(string) || destinationType == typeof(byte[]);
		}

		public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
		{
			if (null == value)
			{
				return null;
			}

			if (value is string)
			{
				return IPAddress.Parse((string)value);
			}
			if (value is byte[])
			{
				return new IPAddress((byte[])value);
			}

			return base.ConvertFrom(context, culture, value);
		}

		public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
		{
			if (null == destinationType)
			{
				throw new ArgumentNullException("destinationType");
			}

			if (null != value && value is IPAddress)
			{
				IPAddress ip = (IPAddress)value;
				if (destinationType == typeof(string))
				{
					return ip.ToString();
				}
				if (destinationType == typeof(byte[]))
				{
					return ip.GetAddressBytes();
				}
				if (destinationType == typeof(InstanceDescriptor))
				{
					Type[] types = new Type[] { typeof(string) };
					object[] values = new object[] { ip.ToString() };
					MemberInfo member = typeof(IPAddress).GetMethod("Parse", BindingFlags.Public | BindingFlags.Static, null, types, null);

					return new InstanceDescriptor(member, values);
				}
			}

			return base.ConvertTo(context, culture, value, destinationType);
		}

	}
}
